package fr.unice.polytech.chord.samples.commands;

import org.objectweb.proactive.api.PAFuture;

import fr.unice.polytech.chord.core.ChordNode;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.core.Tracker;
import fr.unice.polytech.chord.core.messages.asynchronous.GetEntryMessage;
import fr.unice.polytech.chord.core.messages.asynchronous.RemoveEntryMessage;
import fr.unice.polytech.chord.core.responses.asynchronous.EntryResponseMessage;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 12/06/2009
 */
public class RemoveCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public RemoveCommand(Manager manager) {
		super(manager, "Removes an entry on the overlay by using key",
				new String[] { "remove", "rm" }, new String[] { "key" });
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		Key key = null;
		try {
			key = new Key(Integer.parseInt(args[0]));
		} catch (Exception e) {
			super.printInfo("Key argument must be a number");
			return;
		}
		Tracker remoteTracker = super.getManager().getTracker();

		if (args.length == 1) {
			if (remoteTracker.getNumberOfPeersManaged() == 0) {
				super.printInfo("There is no peer on the overlay");
			} else {
				ChordNode node = remoteTracker.getRandomPeer().findSuccessor(
						key);
				String entryFound = ((EntryResponseMessage) PAFuture
						.getFutureValue(node.receive(new GetEntryMessage(key))))
						.getEntryFound().getValue();

				if (entryFound != null) {
					node.receive(new RemoveEntryMessage(key));
					super.printInfo("Key " + key + " with associated value '"
							+ entryFound + "' has been removed from node "
							+ node.getKey());
				} else {
					super.printInfo("No entry found on the overlay with key "
							+ key);
				}
			}
		} else {
			super
					.printInfo("Remove operation must have one argument which is the key to remove.");
		}
	}
}
